import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource, Cluster } from "ol/source";
import { Circle as CircleStyle, Fill, Stroke, Style, Text } from "ol/style";
import { boundingExtent } from "ol/extent.js";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";
export default class clusterPoint {
	constructor(ol) {
		this.ol = ol;

		this.distanceInput = 10;
		this.minDistanceInput = 10;
	}
	init() {
		this.features = [];

		//造点

		for (let i = 0; i < 500; i++) {
			let coord = [
				102.71 + Number(((Math.random() * 50) / 10000).toFixed(6)),
				25.03 + Number(((Math.random() * 50) / 10000).toFixed(6)),
			];

			const point = new Point(coord);
			const feature = new Feature(point);

			this.features.push(feature);
		}

		const source = new VectorSource({
			features: this.features,
		});
		const clusterSource = new Cluster({
			distance: parseInt(this.distanceInput, 10),
			minDistance: parseInt(this.distanceInput, 10),
			source: source,
		});
		const styleCache = {};
		this.vectorLayer = new VectorLayer({
			source: clusterSource,
			style: function (feature) {
				const size = feature.get("features").length;
				// console.log('feature.get("features")', feature.get("features"));
				let style = styleCache[size];
				if (!style) {
					style = new Style({
						image: new CircleStyle({
							radius: 5,
							fill: new Fill({
								color: "rgba(121, 186, 217, 0.2)",
							}),
							stroke: new Stroke({
								color: "rgba(121, 186, 217, 1)",
								width: 2,
							}),
						}),
						text: new Text({
							font: "normal 12px 黑体",
							// // 对其方式
							textAlign: "center",
							// 基准线
							textBaseline: "middle",
							offsetY: -35,
							offsetX: 0,
							backgroundFill: new Stroke({
								color: "rgba(121, 186, 217,0.7)",
							}),
							// 文本填充样式
							fill: new Fill({
								color: "rgba(255,255,255,1)",
							}),
							padding: [5, 5, 5, 5],
							text: `${size}`,
						}),
					});
					styleCache[size] = style;
				}
				return style;
			},
		});
		// this.vectorLayer.setZIndex(9999);
		this.ol.addLayer(this.vectorLayer);
		this.clickMap();
	}
	clickMap() {
		this.ol.on("click", (e) => {
			this.vectorLayer.getFeatures(e.pixel).then((clickedFeatures) => {
				console.log("clickedFeatures", clickedFeatures);
				if (clickedFeatures.length) {
					// Get clustered Coordinates
					const features = clickedFeatures[0].get("features");
					// console.log("features", features);
					if (features.length > 1) {
						const extent = boundingExtent(
							features.map((r) => r.getGeometry().getCoordinates())
						);
						this.ol
							.getView()
							.fit(extent, { duration: 1000, padding: [50, 50, 50, 50] });
					}
				}
			});
		});
	}
}
